var needAdvanceProjectStore = null;
var needAdvancePremisesStore = null;
var needAdvanceBuildingStore = null;
var needAdvanceUnitStore = null;
var needAdvanceRoomStore = null;
var advanceGridStore = null;

Ext.define('component.marketing.needAdvance', {
	extend : 'Ext.form.Panel',
	initComponent:function(){
		
		//项目
		needAdvanceProjectStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "projectName"],
	        proxy:{
	            type:'ajax',
	            url:contextPath+'/estate/project/findProjectList?needAuth=T&resourcesCode=menu_0003_0001',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              }
	        } ,
	        autoLoad: false
		});
		needAdvanceProjectStore.load({
			callback:function(records, options, success){
				var count = needAdvanceProjectStore.getCount();
				if(count>0){
					var id = needAdvanceProjectStore.getAt(0).get("id");
					Ext.getCmp('needAdvanceProjectStore').setValue(id)
				}
				if(Ext.Array.contains(idata,"fin:list:all")){
					var data = {"projectName": "全部", "id": '-1'};
					var rs = Ext.create(data);
					needAdvanceProjectStore.insert(count+1, rs);
				}
			}
		});
		//组团
		needAdvancePremisesStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "groupName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectPremises/findPremisesList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		
		needAdvancePremisesStore.on("beforeload", function(){
			needAdvancePremisesStore.removeAll();
			needAdvanceBuildingStore.removeAll();
			needAdvanceUnitStore.removeAll();
			needAdvanceRoomStore.removeAll();
			Ext.getCmp("needAdvancePremisesStore").setValue("");
			Ext.getCmp("needAdvanceBuildingStore").setValue("")
			Ext.getCmp("needAdvanceUnitStore").setValue("")
			Ext.getCmp("needAdvanceRoomStore").setValue("")
			var projectId = Ext.getCmp("needAdvanceProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			needAdvancePremisesStore.proxy.extraParams.projectId = projectId;
		});
		//楼栋
		needAdvanceBuildingStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "buildingName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectBuilding/findBuildingList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		needAdvanceBuildingStore.on("beforeload", function(){
			needAdvanceBuildingStore.removeAll();
			needAdvanceUnitStore.removeAll();
			needAdvanceRoomStore.removeAll();
			Ext.getCmp("needAdvanceBuildingStore").setValue("")
			Ext.getCmp("needAdvanceUnitStore").setValue("")
			Ext.getCmp("needAdvanceRoomStore").setValue("")
			var projectId = Ext.getCmp("needAdvanceProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("needAdvancePremisesStore").getValue();
			needAdvanceBuildingStore.proxy.extraParams.projectId = projectId;
			needAdvanceBuildingStore.proxy.extraParams.premisesId = premisesId;
		});
		//单元
		needAdvanceUnitStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "unitName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectUnit/findUnitList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		needAdvanceUnitStore.on("beforeload", function(){
			needAdvanceUnitStore.removeAll();
			needAdvanceRoomStore.removeAll();
			Ext.getCmp("needAdvanceUnitStore").setValue("")
			Ext.getCmp("needAdvanceRoomStore").setValue("")
			var projectId = Ext.getCmp("needAdvanceProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("needAdvancePremisesStore").getValue();
			var buildingId = Ext.getCmp("needAdvanceBuildingStore").getValue();
			needAdvanceUnitStore.proxy.extraParams.projectId = projectId;
			needAdvanceUnitStore.proxy.extraParams.premisesId = premisesId;
			needAdvanceUnitStore.proxy.extraParams.buildingId = buildingId;
		});
		//房间
		needAdvanceRoomStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "roomName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectRoom/findRoomList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		needAdvanceRoomStore.on("beforeload", function(){
			needAdvanceRoomStore.removeAll();
			Ext.getCmp("needAdvanceRoomStore").setValue("")
			var projectId = Ext.getCmp("needAdvanceProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("needAdvancePremisesStore").getValue();
			var buildingId = Ext.getCmp("needAdvanceBuildingStore").getValue();
			var unitId = Ext.getCmp("needAdvanceUnitStore").getValue();
			needAdvanceRoomStore.proxy.extraParams.projectId = projectId;
			needAdvanceRoomStore.proxy.extraParams.premisesId = premisesId;
			needAdvanceRoomStore.proxy.extraParams.buildingId = buildingId;
			needAdvanceRoomStore.proxy.extraParams.unitId = unitId;
		});
		
	    //员工list
	    var needAdvanceUserList = new Ext.data.Store({
	        fields: ["userName", "id"],
	        proxy:{
	            type:'ajax',
	            url:jypath+'/customer/customer/userByProjectIdForGroup',
	            reader:{
                    type: 'json', 
                    root: 'root'  //数据
               }
	        },
	        autoLoad: false
        });

        needAdvanceUserList.on("beforeload", function(){
			var projectId = Ext.getCmp("needAdvanceProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
				return false;
			}
            needAdvanceUserList.proxy.extraParams.projectId = projectId;
		});
	    
		var advanceForm = Ext.create("Ext.form.Panel", {
		    title: "查询条件",
		    collapsible: true,  //可折叠
		    autoScroll: false,   //自动创建滚动条
		    defaultType: 'textfield',
		    defaults: {
		    	 anchor: '100%'
		    },
		    fieldDefaults: {
		        margin: 2,
		        labelWidth: 80,
                labelAlign: "right",
                margin: "0 0 10 0"
		    },
		    items: [
		            { xtype: "hiddenfield", name: "docType", value: "0"},
                	{ xtype: "hiddenfield", name: "businessType", id: "businessType", value: "2"},
                	{ xtype: "hiddenfield", name: "housingFundType", value: "45"},
		            {
					    xtype: "container",
					    layout: "hbox",
					    items: [
							{  
					            xtype:'combobox',
					            id:'needAdvanceProjectStore',
					            name: "projectId",
					            store: needAdvanceProjectStore,
					            valueField: "id",  
					            displayField: "projectName",
					            fieldLabel:'所属项目',
					            queryMode:'local',
					            typeAhead: true,
					            listeners:{
					            	'change':function(value){
					            		//加载组团数据
					            		if(value.lastValue && value.lastValue != "-1"){
                                            needAdvanceUserList.load();
					            			needAdvancePremisesStore.load({
					            				callback: function(records, operation, success){
					            					//若无组团数据，加载楼栋
					            					var recordLen = records.length;
					            					if(recordLen == 0){
					            						needAdvanceBuildingStore.load();
					            					}
					            				}
					            			});
					            		}else{
                                            needAdvanceUserList.removeAll();
					            			needAdvancePremisesStore.removeAll();
					            			needAdvanceBuildingStore.removeAll();
					            			needAdvanceUnitStore.removeAll();
					            			needAdvanceRoomStore.removeAll();
					            			Ext.getCmp("needAdvancePremisesStore").setValue("");
					            			Ext.getCmp("needAdvanceBuildingStore").setValue("")
					            			Ext.getCmp("needAdvanceUnitStore").setValue("")
					            			Ext.getCmp("needAdvanceRoomStore").setValue("")
					            		}
					            	}
					            }
					        },
							{  
					            xtype:'combobox',
					            id:'needAdvancePremisesStore',
					            name: "premisesId",
					            store: needAdvancePremisesStore,
					            valueField: "id",  
					            displayField: "groupName",
					            queryMode:'local',
					            typeAhead: true,
					            listeners:{
					            	'change':function(value){
					            		//加载楼栋
					            		//若无楼栋数据，加载单元
					            		if(value.lastValue && value.lastValue != "-1"){
					            			needAdvanceBuildingStore.load({
					            				callback: function(records, operation, success){
					            					//若无组团数据，加载楼栋
					            					var recordLen = records.length;
					            					if(recordLen == 0){
					            						needAdvanceUnitStore.load();
					            					}
					            				}
					            			});
					            		}
					            	}
					            }
					        },
							{  
					            xtype:'combobox',
					            id:'needAdvanceBuildingStore',
					            name: "buildingId",
					            store: needAdvanceBuildingStore,
					            valueField: "id",  
					            displayField: "buildingName",
					            queryMode:'local',
					            typeAhead: true,
					            listeners:{
					            	'change':function(value){
					            		//加载单元
					            		//若无单元数据，加载房间
					            		if(value.lastValue && value.lastValue != "-1"){
					            			needAdvanceUnitStore.load({
					            				callback: function(records, operation, success){
					            					//若无组团数据，加载楼栋
					            					var recordLen = records.length;
					            					if(recordLen == 0){
					            						needAdvanceRoomStore.load();
					            					}
					            				}
					            			});
					            		}
					            	}
					            }
					        },
							{  
					            xtype:'combobox',
					            id:'needAdvanceUnitStore',
					            name: "unitId",
					            store: needAdvanceUnitStore,
					            valueField: "id",  
					            displayField: "unitName",
					            queryMode:'local',
					            typeAhead: true,
					            listeners:{
					            	'change':function(value){
					            		//加载房间
					            		if(value.lastValue && value.lastValue != "-1"){
					            			needAdvanceRoomStore.load();
					            		}
					            	}
					            }
					        },
							{  
					            xtype:'combobox',
					            id:'needAdvanceRoomStore',
					            name: "roomId",
					            store: needAdvanceRoomStore,
					            valueField: "id",  
					            displayField: "roomName",
					            queryMode:'local',
					            typeAhead: true
					        }
			        	]
					},
		            {
						xtype: "container",
						layout: "hbox",
						items: [
							{
							  	xtype:'combobox',
                                fieldLabel:'经&nbsp;&nbsp;纪&nbsp;人',
							  	store:needAdvanceUserList,
							  	displayField: "userName",
							  	valueField:"id",
							  	name:'createUserId'
							}
						]
	            	},
					{
						 xtype: "container",
							layout: "hbox",
							items: [
								{ xtype: "textfield", name: "relationCode", fieldLabel: "业务编号"},
								{ xtype: "textfield", name: "customer_name", fieldLabel: "客户名称"}
							]
	            	},{
						 xtype: "container",
						 layout: "hbox",
						 items:[
							{
								xtype:'container',
								layout:'hbox',
								items:[{
									xtype:'datefield',
									fieldLabel:'开始有效日期',
									name:'ysDateStart',
									format: 'Y-m-d'
								},{
									xtype:'datefield',
									name:'ysDateEnd',
									format: 'Y-m-d',
									fieldLabel:'结束有效日期'
								}]
							}
						 ]
	            	}
		    ],
		    buttons: [
	  	        {
	  	        	xtype: "button", text: "查询",
	  	        	handler:function(){
                        advanceGridStore.getProxy().extraParams.businessType = Ext.getCmp('businessType').getValue();
                        advanceGridStore.load();
	  	        		var pagingTool=Ext.getCmp("needAdvancePagingTool");
	  	        		pagingTool.moveFirst();//跳至第一页
	  	        	}  
	  	        },{
	  	        	 xtype: "button", text: "导出", hidden:finNeedReceiveExport,
					 handler:function(){
	  	        		var count = advanceGrid.getStore().getCount();
	  	        		if(count<=0){
	  	        			Ext.MessageBox.alert("系统提示","没有可导出的数据");
	  	        		}else{
                            advanceGridStore.getProxy().extraParams.businessType = Ext.getCmp('businessType').getValue();
		  	        		var value = encodeURI(encodeURI(JSON.stringify(advanceGridStore.getProxy().extraParams),"utf-8"));
		  	        		var url = jypath + "/marketing/needReceiveRefund/needAdvanceRefundExport?json="+value;
		  	        		location.href = url;
	  	        		}
	  	        	 }
	  	        },
	  	        { xtype: "button", text: "清空",handler:function(){
                        advanceForm.getForm().reset();
	  	        	}
	  	        }
	  	    ]    
		});

		advanceGridStore = Ext.create('Ext.data.Store', {
			fields: ["relationId", "businessType", "relationCode", "customer_name", "customerFamilyName", "combined_name", "price", "totalPrice",
					 "calculatArea", "relationType", "totalReceivablesAmount", "receivablesDate",
					 "receivedAmount", "uncollectedAmount", "signId","id"],
			pageSize: 10,  //页容量15条数据
			//是否在服务端排序 （true的话，在客户端就不能排序）
			remoteSort: false,
			proxy: {
				type: 'ajax',
				url: jypath+'/marketing/needReceiveRefund/advanceList?resourcesCode=menu_0003_0001',
				actionMethods: { read: 'POST' },
				reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
					type: 'json', //返回数据类型为json格式
					root: 'rows',  //数据
					totalProperty: 'total' //数据总条数
				}
			},
			autoLoad: true  //即时加载数据
		});

		advanceGridStore.on("beforeload",function(){
			Ext.apply(advanceGridStore.proxy.extraParams,advanceForm.getForm().getValues());
			var projectId = Ext.getCmp("needAdvanceProjectStore").getValue();
			if(projectId == "-1"){
				advanceGridStore.proxy.extraParams.projectId = "";
			}
			var newResCode = "menu_0003_0001";
			advanceGridStore.proxy.extraParams.resourcesCode = newResCode;
		});
	
		var advanceGrid = Ext.create('Ext.grid.Panel', {
			minHeight:450,
			minWidth:300,
			store: advanceGridStore,
			columnLines: true,
			columns: [{
				text : "操作",
				dataIndex: 'actioncolumn',
				width:100,
				locked   : true,
				renderer : function(value,cellmeta,record,rowIndex,columnIndex,store) {
					var rec = advanceGrid.getStore().getAt(rowIndex);
					//收款
					var url = "";
					var html = "";
					if(rec.get('businessType') == "2"){
						//签约
						url = "/marketing/proceeds/advance?id="+rec.get('id')+"&1=1";
						var tabKey = "advance_pay"+rec.get('id');
						html = "<a href='javascript:parent.openMenu(\"0\",\""+tabKey+"\",\"\",\"收支管理\",\""+url+"\")' style='cursor:pointer'>收款</a>&nbsp;&nbsp;";
					}
					return html;
				}
			},{
				text: '业务编号',
				dataIndex: 'relation',
				renderer : function(value,cellmeta,record,rowIndex,columnIndex,store) {
					var rec = advanceGrid.getStore().getAt(rowIndex);
					var url = "";
					if(rec.get('businessType') == "0"){
						//认筹
						url = jypath+"/customer/payDeposit/toView?id="+rec.get('relationId')+'&returnUrl=,marketing,needReceiveRefund,index';
					}else if(rec.get('businessType') == "1"){
						//认购
						url = jypath+"/customer/subscribe/toView?id="+rec.get('relationId')+'&returnUrl=,marketing,needReceiveRefund,index';
					}else if(rec.get('businessType') == "2"){
						//签约
						url = jypath+"/customer/signed/toView?id="+rec.get('relationId')+'&returnUrl=,marketing,needReceiveRefund,index';
					}else if(rec.get('businessType') == "3"){
						//面积补差
						url = jypath+"/marketing/reserveArea/reserveAreaDetail?id="+rec.get('relationId');
					}
					var html = '<a href="'+url+'" style="cursor:pointer">'+rec.get('relationCode')+'</a>';
					return html;
				}
			},{
				text     : '客户名称',
				dataIndex: 'customer_name'
			},{
				text     : '共同购房者',
				dataIndex: 'customerFamilyName'
			},{
				text     : '房号',
				dataIndex: 'combined_name',
				width    : 240
			},{
				text     : '签约面积(㎡)',
				dataIndex: 'calculatArea'
			},{
				text     : '签约单价(元)',
				dataIndex: 'price'
			},{
				text     : '签约金额(元)',
				dataIndex: 'totalPrice'
			},{
				text     : '房款类型',
				dataIndex: 'relationType'
			},{
				text     : '应收金额(元)',
				dataIndex: 'totalReceivablesAmount'
			},{
				text     : '应收日期',
				dataIndex: 'receivablesDate',
				renderer:function(value){
					if(value != "" && value != null && value != "null"){
						return Ext.Date.format(new Date(value),'Y-m-d');
					}else{
						return "";
					}
				}
			},{
				text     : '已收金额(元)',
				dataIndex: 'receivedAmount'
			},{
				text     : '未收金额(元)',
				dataIndex: 'uncollectedAmount'
			}],
			title: '待收垫付首期明细列表',
			dockedItems: [{
				xtype: 'pagingtoolbar',
				store: advanceGridStore,   // GridPanel中使用的数据
				dock: 'bottom',
				displayInfo: true,
				emptyMsg:"没有数据",
				displayMsg:"显示从{0}条数据到{1}条数据，共{2}条数据",
				id:'needAdvancePagingTool'
			}
			]
		});
	
		
		var defaultConfigg = {
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true,  //可以折叠
		        },
				items:[advanceForm,advanceGrid]
		};
		Ext.apply(this,defaultConfigg);
		this.callParent(arguments);
		
	}
});





